package org.minuframework.file;

import java.io.File;
import java.util.List;
import org.minuframework.exception.ExceptionFailed;
import com.google.common.collect.Lists;

public class Files {

    public static final String DEFAULT_OPERATOR = "*";
    public static final String FILE_OPERATOR = "\\\\";

    public static Directory read(File file) throws ExceptionFailed {
        return read(file, null);
    }

    public static Directory read(File file, File parent) throws ExceptionFailed {
        if (exists(file)) {
            if (file.isDirectory()) {
                File[] fileArr = file.listFiles();
                Directory directory = new Directory(file.toString());
                for (File f : fileArr) {
                    if (f.isDirectory()) {
                        if (isDirectory(parent)) {
                            if (isAddFile(f, parent)) {
                                directory.getDirectories().add(read(f));
                            }
                        } else {
                            directory.getDirectories().add(read(f));
                        }
                    } else {
                        readFiles(file, f, parent, directory);
                    }
                }
                return directory;
            } else {
                return new Directory(file.getParent(), file.getName());
            }
        } else {
            throw new ExceptionFailed("Cannot found Directory from the file " + file);
        }
    }

    public static List<Directory> getDirectories(File file, File parent) throws ExceptionFailed {
        List<Directory> result = Lists.newArrayList();
        Directory directory = read(file, parent);
        for (Directory d : directory.getDirectories()) {
            System.out.println(d);
        }
        return result;
    }

    private static void readFiles(File file, File child, File parent, Directory directory) {
        if (isDirectory(parent)) {
            if (isAddFile(child.getParentFile(), parent)) {
                readFiles(child, parent, directory);
            }
        } else {
            readFiles(child, file, directory);
        }
    }

    private static void readFiles(File file, File parent, Directory directory) {
        if (file.getParent().equals(parent.toString())) {
            directory.getFiles().add(file.getName());
        }
        directory.getDirectories().add(new Directory(file.getParent(), file.getName()));
    }

    public static boolean isAddFile(File file, File parent) {
        return file.toString().equals(parent.toString())
                || file.toString().indexOf(parent.toString()) != -1;
    }

    public static boolean isDirectory(File file) {
        return file != null && file.isDirectory();
    }

    public static boolean isFile(File file) {
        return file != null && file.isFile();
    }

    public static boolean exists(File file) {
        return file != null && file.exists();
    }

}
